#include <arpa/inet.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

int get_listen_fd(char *);

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("please input port\n");
        return -1;
    }
    int tcp_fd = get_listen_fd(argv[1]);


    int epoll_fd = epoll_create(1);
    if(epoll_fd < 0)
    {
      perror("epoll_create fail");
      return -1;
    }

    struct epoll_event event;
    event.data.fd = tcp_fd;
    
    epoll_ctl(epoll_fd,EPOLL_CTL_ADD,tcp_fd,&event);

    return 0;
}

int get_listen_fd(char *port)
{
    int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcp_fd < 0)
    {
        perror("socket errno");
        exit(-1);
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(port));
    inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);

    socklen_t len = sizeof(len);
    int ret = bind(tcp_fd, (struct sockaddr *)&server_addr, len);

    listen(tcp_fd, 5);

    return tcp_fd;
}
